# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告

"""
根据笔记id、用户id。查询用户。笔记、粉丝、获赞与收藏数量
https://www.xiaohongshu.com/discovery/item/5d562deb000000000201c565

https://www.xiaohongshu.com/user/profile/576a611782ec39202e1045b7
"""


class SearchUser():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # 'User-Agent': ua.random,
            # 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Safari/605.1.15',
            'authority': 'www.xiaohongshu.com',
            'method': 'GET',
            'path': '/discovery/item/5d562deb000000000201c565',
            'scheme': 'https',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'max-age=0',
            'cookie': 'xhsTrackerId=746a8966-a9ee-415a-c1e9-1332f0d3629e; extra_exp_ids=gif_clt1|ques_exp1; timestamp1=1698082823; hasaki=JTVCJTIyTW96aWxsYSUyRjUuMCUyMChXaW5kb3dzJTIwTlQlMjAxMC4wJTNCJTIwV2luNjQlM0IlMjB4NjQpJTIwQXBwbGVXZWJLaXQlMkY1MzcuMzYlMjAoS0hUTUwlMkMlMjBsaWtlJTIwR2Vja28pJTIwQ2hyb21lJTJGODEuMC40MDQ0LjEyMiUyMFNhZmFyaSUyRjUzNy4zNiUyMiUyQyUyMnpoLUNOJTIyJTJDMjQlMkMtNDgwJTJDdHJ1ZSUyQ3RydWUlMkN0cnVlJTJDJTIydW5kZWZpbmVkJTIyJTJDJTIyZnVuY3Rpb24lMjIlMkNudWxsJTJDJTIyV2luMzIlMjIlMkM4JTJDOCUyQyUyMjElMjIlMkMlMjJDaHJvbWUlMjBQREYlMjBQbHVnaW4lM0ElM0FQb3J0YWJsZSUyMERvY3VtZW50JTIwRm9ybWF0JTNBJTNBYXBwbGljYXRpb24lMkZ4LWdvb2dsZS1jaHJvbWUtcGRmfnBkZiUzQkNocm9tZSUyMFBERiUyMFZpZXdlciUzQSUzQSUzQSUzQWFwcGxpY2F0aW9uJTJGcGRmfnBkZiUzQk5hdGl2ZSUyMENsaWVudCUzQSUzQSUzQSUzQWFwcGxpY2F0aW9uJTJGeC1uYWNsfiUyQ2FwcGxpY2F0aW9uJTJGeC1wbmFjbH4lMjIlMkMxNDQ4MzQ1NTE0JTVE; timestamp2=f985a1d4ddea568649d9be6462b0a86b; xhs_spses.5dde=*; xhs_eaglet_domain_user_id=a9b3227f-3fcb-4e40-944f-c9a5aa5cc539; Hm_lvt_d0ae755ac51e3c5ff9b1596b0c09c826=1587735171; Hm_lpvt_d0ae755ac51e3c5ff9b1596b0c09c826=1587735171; xhs_spid.5dde=7e8df4db2e92438e.1587735155.1.1587735174.1587735155.b5fb8e58-2d2a-4361-b76b-4004a5a66bbe',
            'dnt': '1',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'none',
            'sec-fetch-user': '?1',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'

        }

    # 根据笔记id查询用户信息：关注数量、粉丝数量、笔记数量、获赞与收藏数量
    def noteIdToInfo(self, noteId):
        url = f"https://www.xiaohongshu.com/discovery/item/{noteId}"
        html = HttpUtils.do_request("GET", url, self.headers, "")
        root = etree.HTML(html.text)
        dict_data = dict()
        dict_data['follows_count'] = re.findall(r"\"follows\":(.*?)\,", html.text, re.M|re.S)[0]  # 关注数量
        dict_data['fans_count'] = re.findall(r"\"fans\":(.*?)\,", html.text, re.M|re.S)[0]  # 粉丝数量
        dict_data['note_count'] = re.findall(r"\"notes\":(.*?)\,", html.text, re.M|re.S)[0]  # 笔记数量
        liked_count = re.findall(r"\"liked\":(.*?)\,", html.text, re.M|re.S)[0]  # 获赞
        collected_count = re.findall(r"\"collected\":(.*?)\,", html.text, re.M|re.S)[0]  # 收藏
        dict_data['liked_collected_count'] = str(int(liked_count) + int(collected_count))  # 获赞与收藏
        # aa = re.findall(r"__INITIAL_SSR_STATE__=(.*?)\<\/script\>", html.text, re.M|re.S)[0]
        str_json = re.findall(r"window\.__INITIAL_SSR_STATE__=(.*?)\<\/script\>", html.text, re.M|re.S)[0]
        str_json = str_json.replace("undefined", "\"undefined\"")
        data_json = json.loads(str_json)

        # dict_data['username'] = root.xpath('//span[@class="name-detail"]/text()')[0]  # 用户名称
        # dict_data['note_count'] = root.xpath('//span[@class="note"]/text()')[0]  # 笔记数量
        # dict_data['fans_count'] = root.xpath('//span[@class="fans"]/text()')[0]  # 粉丝数量
        # dict_data['collect_count'] = root.xpath('//span[@class="collect"]/text()')[0]  # 获赞与收藏
        print(str(dict_data))


    #  根据用户id查询信息：关注数量、粉丝数量、笔记数量、获赞与收藏数量
    def userIdToInfo(self, userId):
        url = f"https://www.xiaohongshu.com/user/profile/{userId}"
        html = HttpUtils.do_request("GET", url, self.headers, "")
        str_json = re.findall(r"window\.__INITIAL_SSR_STATE__=(.*?)\<\/script\>", html.text, re.M|re.S)[0]
        str_json = str_json.replace("undefined", "\"undefined\"")
        data_json = json.loads(str_json)
        dict_data = dict()
        dict_data['id'] = data_json['Main']['userDetail']['id']  # 用户id
        dict_data['nickname'] = data_json['Main']['userDetail']['nickname']  # 用户名
        dict_data['desc'] = data_json['Main']['userDetail']['desc']  # 简介
        dict_data['follows'] = data_json['Main']['userDetail']['follows']  # 关注数量
        dict_data['fans'] = data_json['Main']['userDetail']['fans']  # 粉丝数量
        dict_data['notes'] = data_json['Main']['userDetail']['notes']  # 笔记数量
        dict_data['boards'] = data_json['Main']['userDetail']['boards']  # 专辑数量
        dict_data['liked'] = data_json['Main']['userDetail']['liked']  # 获赞数量
        dict_data['collected'] = data_json['Main']['userDetail']['collected']  # 收藏数量
        dict_data['liked_collected_count'] = str(int(dict_data['liked']) + int(dict_data['collected']))  # 收藏数量
        # # 正则直接查找
        # dict_data['follows_count'] = re.findall(r"\"follows\":(.*?)\,", html.text, re.M|re.S)[0]  # 关注数量
        # dict_data['fans_count'] = re.findall(r"\"fans\":(.*?)\,", html.text, re.M|re.S)[0]  # 粉丝数量
        # dict_data['note_count'] = re.findall(r"\"notes\":(.*?)\,", html.text, re.M|re.S)[0]  # 笔记数量
        # liked_count = re.findall(r"\"liked\":(.*?)\,", html.text, re.M|re.S)[0]  # 获赞
        # collected_count = re.findall(r"\"collected\":(.*?)\,", html.text, re.M|re.S)[0]  # 收藏
        # dict_data['liked_collected_count'] = str(int(liked_count) + int(collected_count))  # 获赞与收藏
        print(str(dict_data))


    # 根据分享链接提取用户、笔记信息
    def get_share(self, url):
        html = HttpUtils.do_request("GET", url, self.headers, "")
        str_json = re.findall(r"window\.__INITIAL_SSR_STATE__=(.*?)\<\/script\>", html.text, re.M|re.S)[0]
        str_json = str_json.replace("undefined", "\"undefined\"")
        data_json = json.loads(str_json)
        dict_data = dict()
        dict_data['id'] = data_json['NoteView']['noteInfo']['user']['id']  # 用户id
        dict_data['nickname'] = data_json['NoteView']['noteInfo']['user']['nickname']  # 用户名
        dict_data['desc'] = data_json['NoteView']['noteInfo']['user']['desc']  # 简介
        dict_data['follows'] = data_json['NoteView']['noteInfo']['user']['follows']  # 关注数量
        dict_data['fans'] = data_json['NoteView']['noteInfo']['user']['fans']  # 粉丝数量
        dict_data['notes'] = data_json['NoteView']['noteInfo']['user']['notes']  # 笔记数量
        dict_data['boards'] = data_json['NoteView']['noteInfo']['user']['boards']  # 专辑数量
        dict_data['liked'] = data_json['NoteView']['noteInfo']['user']['liked']  # 获赞数量
        dict_data['collected'] = data_json['NoteView']['noteInfo']['user']['collected']  # 收藏数量
        dict_data['liked_collected_count'] = str(int(dict_data['liked']) + int(dict_data['collected']))  # 收藏数量
        # 该笔记信息
        dict_data['likes'] = data_json['NoteView']['noteInfo']['likes']  # 笔记点赞数量
        dict_data['comments'] = data_json['NoteView']['noteInfo']['comments']  # 笔记评论数量
        dict_data['collects'] = data_json['NoteView']['noteInfo']['collects']  # 笔记收藏数量
        dict_data['title'] = data_json['NoteView']['noteInfo']['title']  # 笔记标题
        dict_data['time'] = data_json['NoteView']['noteInfo']['time']  # 笔记时间


if __name__ == '__main__':
    searchUser = SearchUser()
    noteId = "5e8191ba000000000100704e"
    print(f"============{noteId}=============")

    # 根据用户id查询信息：关注数量、粉丝数量、笔记数量、获赞与收藏数量
    # searchUser.userIdToInfo("576a611782ec39202e1045b7")

    # 根据笔记id查询
    # searchUser.noteIdToInfo(noteId)

    # 根据分享链接提取用户、笔记信息
    searchUser.get_share("http://xhslink.com/XbdWh")